# user操作
from sqlalchemy.orm import Session
from models.user.user_models import User
from sqlalchemy import func
import time

#登录数据库验证
def get_user_by_username_and_pwd(db:Session,username:str,md5_pwd:str) -> User:
    user = db.query(User.id,User.state).filter(User.username == func.binary(username),User.pwd == md5_pwd).first()

    return user



#验证是否登录从token 解析出id
def get_user_by_id(db:Session,id:int) -> User:

    user = db.query(User.id,User.username,User.avatar,User.create_time,User.dep_id,User.state).filter(User.id == id).first()
    return user



#用户列表（分页逻辑）
# page_size   显示几条数据
# currentPage  第几页
def get_user_pagenation(db:Session,page_size:int,currentPage:int) -> [User]:
   users = db.query(User.id,User.username,User.create_time,User.dep_id,User.state,User.addr,User.avatar).limit(page_size).offset((currentPage-1)*page_size).all()

   return users

#总数据量
def get_user_total(db:Session) -> int:
    total = db.query(User).count()
    return total



#启用用户 和 停用用户各个数量
def get_user_state_total(db:Session):
    y_total = db.query(User).filter(User.state == "1").count() #启用
    n_total = db.query(User).filter(User.state == "0").count() #停用

    return {'y_total':y_total,'n_total':n_total}


# 启用停用逻辑
def active(db:Session,id:int,state:int):
    user = db.query(User).filter(User.id == id).first() #找出对应的用户
    if user:
        #判断有没有用户,有则改
        user.state = state
        #提交修改
        db.commit()
        db.flush()

    else:
        # 没有则报错
        return {'code':500,'msg':'没有这个用户'}

#编辑用户逻辑
def user_info_updata(db:Session,id:int,user_data):
    user = db.query(User).filter(User.id == id).first()
    print(id,User.id)
    #查询完毕后修改数据
    user.id = user_data.id
    user.username = user_data.username
    user.addr = user_data.addr
    user.create_time =  user_data.create_time
    user.state = user_data.state
    user.dep_id = user_data.dep_id
    user.avatar = user_data.avatar
    # 提交修改
    db.commit()
    db.flush()


#删除用户
def user_info_del(db: Session,id:int):
    user = db.query(User).filter(User.id == id).first()
    db.delete(user)  #删除
#     提交修改
    db.commit()
    db.flush()



#添加用户
def add_users(db:Session,user):
   #添加数据
   create_times = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
   data = User(
        username = user.username,
        pwd = "e10adc3949ba59abbe56e057f20f883e",
        avatar =  user.avatar,
        addr = user.addr,
        state = user.state,
        create_time = create_times
   )
   db.add(data)
   db.commit()
   db.flush()




